package ru.ccfit.nsu.g7204.dronov.adPlatform;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Drongo
 * Date: 15.03.11
 * Time: 12:43
 * To change this template use File | Settings | File Templates.
 */
public class NetworkInterfaceManager {
    private NetworkInterface anInterface;
    private NetworkInterfaceListener interfaceListener;
    private int port;

    public NetworkInterfaceManager(int port, NetworkInterfaceListener nilistener) {
        this.port=port;
        interfaceListener=nilistener;
        anInterface=null;
    }

    public void startInterface()
    {
        if (anInterface==null || !anInterface.isWorking())
        {
            try {
                anInterface=new NetworkInterface(port,interfaceListener);
                Thread thread = new Thread(anInterface);
                anInterface.setWorking(true);
                thread.start();
            }
            catch (IOException e)
            {
                ru.ccfit.nsu.g7204.dronov.adPlatform.utils.LoggingUtils.error(e.getLocalizedMessage(),e);
            }
        }
    }

    public void stopInterface()
    {
        if (anInterface==null)
            return;
        if (anInterface.isWorking())
        {
            anInterface.setWorking(false);
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port=port;
        boolean  stopped =false;
        if (anInterface.isWorking())
        {
            stopInterface();
            stopped=true;
        }
        if (stopped)
            startInterface();
    }
}
